<template>
    <div ref="checkboxGroupRef" class="pe-checkbox-group" :id="id">
        <slot></slot>
    </div>
</template>

<script setup lang="ts">
import { provide, ref, watch, nextTick } from "vue"
import { getId } from "../../utils/commonUtil"

const value = defineModel<(number | string)[]>({ default: [] })

const id = ref<string>(`pe-checkbox-${getId()}`)

/**
 * @param size 多选框组尺寸
 * @param disabled 是否禁用
 * @param min 可被勾选的 checkbox 的最小数量
 * @param max 可被勾选的 checkbox 的最大数量
 */
interface Props {
    size?: 'default' | 'small' | 'large',
    disabled?: boolean,
    min?: number,
    max?: number
}

const props = withDefaults(defineProps<Props>(), {
    disabled: false
})

const emits = defineEmits(["change"])

const checkboxSize = ref<'default' | 'small' | 'large'>()
const checkboxDisabled = ref<boolean>(false)

// 禁用多选框
const disabledArr = ref<(string | number)[]>([])

const checkboxGroupRef = ref<HTMLDivElement>()

watch([props, value], ([newProps, newValue]) => {
    checkboxSize.value = newProps.size
    checkboxDisabled.value = newProps.disabled
    disabledArr.value = []
    const size = newValue.length
    if (typeof newProps.min === 'number') {
        if (size >= newProps.min) {
            for (let i = 0; i < newProps.min; i++) {
                disabledArr.value.push(newValue[i])
            }
        }
    }
    if (typeof newProps.max === 'number') {
        if (size >= newProps.max) {
            nextTick(() => {
                const flag = typeof newValue[0] === 'number'
                let arr: (string | number)[] = []
                const inputList = checkboxGroupRef.value?.querySelectorAll<HTMLInputElement>(`[name=${id.value}]`)
                inputList?.forEach(item => {
                    if (item.checked) {
                        item.disabled = false
                    } else {
                        if (flag) {
                            arr.push(Number(item.value))
                        } else {
                            arr.push(item.value)
                        }
                    }
                })
                disabledArr.value = arr
            })
        }
    }
}, { immediate: true })

const onChange = (val: Array<string | number>) => {
    emits("change", val)
}

provide("pe-checkbox-id", id)
provide("pe-checkbox-value", value)
provide("pe-checkbox-size", checkboxSize)
provide("pe-checkbox-disabled", checkboxDisabled)
provide("pe-checkbox-disabledArr", disabledArr)
provide("pe-checkbox-change", onChange)
</script>

<script lang="ts">
export default {
    name: "pe-checkbox-group"
}
</script>